<template>
  <div>
    <el-card>
      <el-form inline>
        <el-form-item label="一级分类">
          <el-select
            placeholder="请选择"
            v-model="$store.state.category.category1Id"
          >
            <el-option
              v-for="c1 in category1List"
              :key="c1.id"
              :value="c1.id"
              :label="c1.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select
            placeholder="请选择"
            size="small"
            v-model="$store.state.category.category2Id"
          >
            <el-option
              v-for="c2 in category2List"
              :key="c2.id"
              :value="c2.id"
              :label="c2.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="三级分类">
          <el-select
            placeholder="请选择"
            size="small"
            v-model="$store.state.category.category3Id"
          >
            <el-option
              v-for="c3 in category3List"
              :key="c3.id"
              :value="c3.id"
              :label="c3.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'CategorySelector',

  mounted() {
    this.getCategory1List()
  },

  methods: {
    getCategory1List() {
      this.$store.dispatch('getCategory1List')
    }
  },
  computed: {
    ...mapState({
      category1List: (state) => state.category.category1List,
      category1Id: (state) => state.category.category1Id,
      category2List: (state) => state.category.category2List,
      category2Id: (state) => state.category.category2Id,
      category3List: (state) => state.category.category3List,
      category3Id: (state) => state.category.category3Id
    })
  },
  watch: {
    category1Id(newVal, oldVal) {
      if (!newVal) return
      this.$store.dispatch('getCategory2List', newVal)
    },
    category2Id(newVal, oldVal) {
      if (!newVal) return
      this.$store.dispatch('getCategory3List', this.category2Id)
    }
  }
}
</script>

<style lang="less" scoped></style>
